package com.phpxiu.app.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.phpxiu.app.adapter.HomeDiscoverListAdapter;
import com.phpxiu.app.adapter.holder.HomeDiscoverViewHolder;
import com.phpxiu.app.api.callback.EnterRoomChecker;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.controller.avcontroller.QavsdkControl;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.CurLiveInfo;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.list.HomeDiscover;
import com.phpxiu.app.model.response.HomeDiscListMode;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.pulltorefresh.PullToRefreshListView;
import com.phpxiu.app.pulltorefresh.PullToRefreshView;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.RoomVideoRoom;
import com.phpxiu.app.view.custom.ListEmptyView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by WuJinZhou on 2016/5/5.
 */
public class HomeDiscoverFragment extends BaseFragment implements PullToRefreshView.OnRefreshListener2<ListView>,AdapterView.OnItemClickListener {
    public final static String TAG="HomeDiscoverFragment";
    private final static int HANDLE_REFRESH_COMPLETE=0x1;
    private boolean isInit=false;
    private PullToRefreshListView ptRefreshView;
    private ListView mListView;
    private ListEmptyView emptyView;
    private HomeDiscoverListAdapter mAdapter;
    private List<HomeDiscover>records=new ArrayList<HomeDiscover>();
    private int mOpera= HttpConfig.REQUEST_OPERA_INIT;
    private int pageSize=15;//每页取15条记录
    private int currentAllRecords=0;//当前列表刷新时获取的后台记录条数
    private int pageIndex=1;//下一页序号,页数从1开始计数
    private OKHttpParam param;

    public static BaseFragment builder(String arg){
        HomeDiscoverFragment fragment=new HomeDiscoverFragment();
        Bundle b = new Bundle();
        b.putString(ARG,arg);
        fragment.setArguments(b);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView=inflater.inflate(R.layout.home_discover_fragment,null);
        emptyView=new ListEmptyView(getActivity());
        emptyView.setMsg(getString(R.string.list_empty_title));
        init();
        return rootView;
    }

    /**
     * 初始化视图
     */
    private void init(){
        ptRefreshView=(PullToRefreshListView)rootView.findViewById(R.id.home_discover_pull_refresh_list);
        ptRefreshView.setOnRefreshListener(this);
        mListView=ptRefreshView.getRefreshableView();
        mListView.setOnItemClickListener(this);
        mListView.setEmptyView(emptyView);
        mListView.setDivider(null);
        mAdapter=new HomeDiscoverListAdapter(act,records);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onShow() {
        if(!isInit){
            request(mOpera);
        }
    }

    /**
     * 请求数据初始化
     */
    private void request(int opera){
        mOpera=opera;
        if(param==null){
            param=OKHttpParam.builder();
            param.put("pageSize",pageSize);
        }
        param.put("pageIndex",1);
        if(mOpera==HttpConfig.REQUEST_OPERA_LOAD){
            param.put("pageIndex",pageIndex==1?2:pageIndex);
        }
        OKHttp.post(HttpConfig.API_HOME_LATEST_LIST, param.jsonParam(), TAG, new OKHttpUIHandler(HomeDiscListMode.class) {
            @Override
            public void onSuccess(Object model) {
                emptyView.loaded();
                try {
                    HomeDiscListMode m = (HomeDiscListMode) model;
                    KKYUtil.log(TAG, "首页最新直播列表数据：" + m.getResponseStr());
                    if (mOpera == HttpConfig.REQUEST_OPERA_REFRESH || mOpera == HttpConfig.REQUEST_OPERA_INIT) {
                        currentAllRecords = m.getData().getTotalItem();
                        records.clear();
                        pageIndex = 1;
                    } else {
                        if (currentAllRecords > 0 && records.size() > 0 && records.size() < currentAllRecords) {
                            pageIndex++;
                        }
                    }
                    records.addAll(m.getData().getRecordList());
                    mAdapter.notifyDataSetChanged();
                    isInit = true;
                } catch (NullPointerException e) {

                }
                if (ptRefreshView != null) {
                    ptRefreshView.onRefreshComplete();
                }
                listEmpty(records.size() == 0);
            }

            @Override
            public void onErr(String errMsg) {
                isInit = false;
                if (ptRefreshView != null) {
                    ptRefreshView.onRefreshComplete();
                }
                listEmpty(records.size() == 0);
            }
        });
    }

    @Override
    public void handleMsg(Message msg) {
        switch (msg.what){
            case HANDLE_REFRESH_COMPLETE:
                if (ptRefreshView != null) {
                    ptRefreshView.onRefreshComplete();
                }
                break;
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(view.getTag()!=null&&view.getTag() instanceof HomeDiscoverViewHolder){
            HomeDiscover discover=((HomeDiscoverViewHolder)view.getTag()).getDiscover();
            onEnterRoom(discover);
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshView<ListView> refreshView) {
        request(HttpConfig.REQUEST_OPERA_REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshView<ListView> refreshView) {
        if(records.size()!=0&&records.size()<currentAllRecords) {
            request(HttpConfig.REQUEST_OPERA_LOAD);
        }else{
            handler.sendEmptyMessage(HANDLE_REFRESH_COMPLETE);
        }
    }

    /**
     * 进入直播间
     */
    private void onEnterRoom(HomeDiscover room) {
        KKYUtil.log(TAG,"进入直播间："+room.getAvRoomId()+"@"+room.getTitle());
        //SDK实例存在
        if(QavsdkControl.getInstance().getAVContext()!=null){

        }else{
            Toast.makeText(getActivity(),"进入失败，请稍后再试",Toast.LENGTH_LONG).show();
            EnterRoomChecker.getInstance().IMLogin(MySelfInfo.getInstance().getId(),MySelfInfo.getInstance().getUserSig());//重新登录
            return;
        }
        try {
            //如果是自己
            if (room.getHost().getUid().equals(MySelfInfo.getInstance().getId())) {
                Toast.makeText(getActivity(), "this room don't exist", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(getActivity(), RoomVideoRoom.class);
            intent.putExtra(Constants.ID_STATUS, Constants.MEMBER);
            MySelfInfo.getInstance().setIdStatus(Constants.MEMBER);
            CurLiveInfo.setHostID(room.getHost().getUid());
            CurLiveInfo.setHostName(room.getHost().getNickname());
            CurLiveInfo.setHostAvator(room.getHost().getAvatar());
            CurLiveInfo.setRoomNum(Integer.parseInt(room.getAvRoomId()));
            CurLiveInfo.setMembers(Integer.parseInt(room.getWatchCount()) + 1); // 添加自己
            CurLiveInfo.setAdmires(Integer.parseInt(room.getAdmireCount()));
            CurLiveInfo.setAddress(room.getLbs().getAddress());
            startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 空列表,不加载更多
     */
    public void listEmpty(boolean isEmpty){
        if (ptRefreshView != null) {
            if(isEmpty) {
                ptRefreshView.setMode(PullToRefreshView.Mode.PULL_FROM_START);
            }else{
                ptRefreshView.setMode(PullToRefreshView.Mode.BOTH);
            }
        }
    }

    @Override
    public void onDestroyView() {
        records.clear();
        super.onDestroyView();
    }
}
